<template>
  <div class="logs-management">
    <div class="page-header">
      <h1 class="page-title">
        <FileText :size="24" style="margin-right: 12px;" />
        用户操作日志
      </h1>
      <p class="page-description">查看和管理用户操作日志</p>
    </div>

    <div class="content-area">
      <!-- 筛选条件 -->
      <a-card class="filter-card" :bordered="false">
        <a-row :gutter="16">
          <a-col :span="6">
            <a-input
              v-model:value="filterUserId"
              placeholder="输入用户ID"
              style="width: 100%"
            />
          </a-col>
          <a-col :span="6">
            <a-input
              v-model:value="filterOperation"
              placeholder="输入操作类型"
              style="width: 100%"
            />
          </a-col>
          <a-col :span="6">
            <a-button type="primary" @click="handleSearch" :loading="loading">
              <FileText :size="16" style="margin-right: 4px;" />
              搜索
            </a-button>
          </a-col>
          <a-col :span="6">
            <a-button @click="handleRefresh" :loading="loading">
              <RotateCcw :size="16" style="margin-right: 4px;" />
              刷新
            </a-button>
          </a-col>
        </a-row>
      </a-card>

      <!-- 日志列表 -->
      <a-card title="操作日志记录" :bordered="false" style="margin-top: 16px;">
        <a-table
          :columns="columns"
          :data-source="logList"
          :pagination="pagination"
          :loading="loading"
          row-key="id"
          size="small"
          @change="handleTableChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'operateTime'">
              {{ formatDate(record.operateTime) }}
            </template>
            <template v-else-if="column.key === 'params'">
              <div class="log-params" :title="record.params">
                {{ record.params }}
              </div>
            </template>
            <template v-else-if="column.key === 'interface_'">
              <div class="log-interface" :title="record.interface_">
                {{ record.interface_ }}
              </div>
            </template>
            <template v-else-if="column.key === 'deviceInfo'">
              <div class="device-info" :title="record.deviceInfo">
                {{ record.deviceInfo }}
              </div>
            </template>
            <template v-else-if="column.key === 'errorMsg'">
              <div class="error-msg" :title="record.errorMsg">
                {{ record.errorMsg }}
              </div>
            </template>
            <template v-else-if="column.key === 'operateResult'">
              <a-tag :color="record.operateResult === 'SUCCESS' ? 'green' : 'red'">
                {{ record.operateResult }}
              </a-tag>
            </template>
          </template>
        </a-table>
      </a-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { FileText, RotateCcw } from 'lucide-vue-next'
import { message } from 'ant-design-vue'
import { Codewin } from '@/api/generated/Codewin'
import type { UserOperationLogVO, UserOperationLogPageRequest } from '@/api/generated/data-contracts'
import { useAuthStore } from '@/stores'
const authStore = useAuthStore()

const api = new Codewin({
  baseURL: import.meta.env.VITE_API_BASE_URL || 'https://www.codewin.top',
  securityWorker: (securityData) => {
    return authStore.token ? { headers: { Authorization: `Bearer ${authStore.token}` } } : {}
  }
})

// 筛选条件
const filterUserId = ref('')
const filterOperation = ref('')

// 分页和数据
const logList = ref<UserOperationLogVO[]>([])
const loading = ref(false)
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
})

// 表格列定义
const columns = [
  {
    title: '操作时间',
    dataIndex: 'operateTime',
    key: 'operateTime',
    width: 180,
  },
  {
    title: '用户ID',
    dataIndex: 'userId',
    key: 'userId',
    width: 120,
  },
  {
    title: '操作类型',
    dataIndex: 'operateType',
    key: 'operateType',
    width: 120,
  },
  {
    title: '操作接口',
    dataIndex: 'interface_',
    key: 'interface_',
    width: 200,
  },
  {
    title: '操作参数',
    dataIndex: 'params',
    key: 'params',
    width: 200,
  },
  {
    title: 'IP地址',
    dataIndex: 'ip',
    key: 'ip',
    width: 140,
  },
  {
    title: '设备信息',
    dataIndex: 'deviceInfo',
    key: 'deviceInfo',
    width: 200,
  },
  {
    title: '操作结果',
    dataIndex: 'operateResult',
    key: 'operateResult',
    width: 100,
  },
  {
    title: '错误信息',
    dataIndex: 'errorMsg',
    key: 'errorMsg',
    width: 200,
  },
]

// 获取操作日志数据
const fetchLogData = async () => {
  try {
    loading.value = true

    // 直接传递扁平化参数，符合后端 UserOperationLogPageRequest 继承 PageParam 的要求
    const response = await api.getUserOperationLogPage({
      pageRequest: {
        pageNo: pagination.value.current,
        pageSize: pagination.value.pageSize,
        userId: filterUserId.value || undefined,
        operateType: filterOperation.value || undefined,
      },
    
    })

    if (response.data?.code === 0 && response.data.data) {
      logList.value = response.data.data.list || []
      pagination.value.total = response.data.data.total || 0
    } else {
      message.error(response.data?.message || '获取操作日志失败')
    }
  } catch (error) {
    console.error('获取操作日志失败:', error)
    message.error('获取操作日志失败')
  } finally {
    loading.value = false
  }
}

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '-'
  try {
    // 统一格式：去掉T字符，只保留到秒
    return dateString.replace('T', ' ').split('.')[0]
  } catch (error) {
    return dateString
  }
}

// 处理搜索
const handleSearch = () => {
  pagination.value.current = 1
  fetchLogData()
}

// 处理刷新
const handleRefresh = () => {
  fetchLogData()
  message.success('日志已刷新')
}

// 处理分页变化
const handleTableChange = (paginationInfo: any) => {
  pagination.value.current = paginationInfo.current
  pagination.value.pageSize = paginationInfo.pageSize
  fetchLogData()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchLogData()
})
</script>

<style scoped>
.logs-management {
  height: 100vh;
}

.page-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #1a1a1a;
  display: flex;
  align-items: center;
}

.page-description {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.content-area {
  height: calc(100% - 100px);
}

.filter-card {
  margin-bottom: 0;
}

.log-params {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.log-interface {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.device-info {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.error-msg {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

:deep(.ant-card-head) {
  border-bottom: 1px solid #f0f0f0;
}

:deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  font-weight: 600;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background: #f5f5f5;
}
</style>
